﻿<template>
    <div class="hidden h100 flex-column">

        <div class="flex-row h100" style="align-items:flex-start;">
            <div class="hidden-x h100" style="width:350px;">
                <template v-if="list.length>0">
                    <el-tree :data="list" :props="defaultProps" accordion :expand-on-click-node="false" default-expand-all :default-expanded-keys="[1]" node-key="id">
                        <span class="custom-tree-node" slot-scope="{ node, data }" style="flex: 1; display: flex; align-items: center; justify-content: space-between; padding-right: 8px;">
                            <span class="flex-row-fill" v-on:click="nodeClick(data,node)">
                                <i :class="data.hdType==0?'el-icon-folder-opened':'el-icon-document'" style="margin-right:5px;"></i>{{ data.label }}
                            </span>
                            <span>
                                <el-button type="text" v-if="data.hdStatus == 0&&((fn.edit&&data.oiId==optor.openId)||fn.root)" v-on:click="openEdit(2,data,node,data.share)" icon="el-icon-edit">
                                </el-button>
                                <el-button type="text" v-if="data.hdType==0"
                                           v-on:click="openEdit(1,data,node,data.share)" icon="el-icon-plus">
                                </el-button>
                                <el-button type="text" v-if="data.hdPid==0"
                                           v-on:click="loadList" icon="el-icon-refresh">
                                </el-button>
                                <el-button type="text" v-if="data.hdStatus == 0 && ((fn.edit&&data.oiId==optor.openId)||fn.root)" v-on:click="openEdit(3,data,node)" icon="el-icon-delete" style="color:red;">
                                </el-button>
                            </span>
                        </span>
                    </el-tree>
                </template>
                <el-empty v-else>
                    <el-button type="primary" plain icon="el-icon-refresh" size="mini" v-on:click="loadList">刷新</el-button>
                </el-empty>
            </div>
            <div class="flex-row-fill flex-column bg-light">
                <div class="flex-column-fill hidden-x" v-if="list.length>0">
                    <js-media-detail v-if="!!msg" :value="msg"></js-media-detail>
                    <el-empty v-else :image-size="200" class="h100" description="暂无预览"></el-empty>
                </div>
            </div>
        </div>

        <el-drawer custom-class="el-drawer-fix" :visible="drawer.show>0" v-on:close="drawer.show=0" size="800px" :title="drawer.title" :destroy-on-close="true" :close-on-press-escape="false" :wrapper-closable="false">
            <div v-if="drawer.show>0" class="flex-column hidden" style="position:absolute;top:0;bottom:0;left:0;right:0;">
                <div class="flex-column-fill hidden-x" style="padding-bottom:50px;">
                    <el-form ref="form" :model="form" label-width="90px" size="small" class="padding-10" :rules="rules">
                        <el-form-item label="上级目录" v-if="form.hdPtitle">
                            <el-input v-model="form.hdPtitle" readonly></el-input>
                        </el-form-item>
                        <el-form-item label="类型" prop="hdType">
                            <el-select v-model="form.hdType" :disabled="drawer.show==2" placeholder="请选择" filterable :popper-append-to-body="false">
                                <el-option v-for="item in typeList" :label="item.value" :value="item.key"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="名称" prop="hdTitle" required>
                            <el-input v-model="form.hdTitle" placeholder="请输入名称" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="公开" required v-removeAriaHidden>
                            <el-radio-group v-model="form.share" :disabled="form.pshare">
                                <el-radio :label="0" :name="0">公开</el-radio>
                                <el-radio :label="1" :name="1">私有</el-radio>
                            </el-radio-group>
                            @*<el-switch v-model="form.share" active-text="公开" inactive-text="私有" :active-value="0" :inactive-value="1" :disabled="form.pshare==1">
                                </el-switch>*@
                        </el-form-item>
                        <el-form-item label="内容" prop="mediaList" v-if="form.hdType==1">
                            <js-media :value="form.mediaList"></js-media>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="padding-10 border-top-solid border-greyLight">
                    <el-button-group size="small">
                        <el-button type="info" plain v-on:click="drawer.show=0" icon="fa fa-rotate-left" size="small">取 消</el-button>
                        <el-button type="primary" icon="fa fa-check" size="small" v-on:click="submit">保 存</el-button>
                        <el-button type="info" icon="fa fa-eye" v-if="form.hdType==1" v-on:click="view" size="small">预 览</el-button>
                    </el-button-group>
                </div>
                <el-dialog title="预览" :visible.sync="showView" width="375px" :append-to-body="true" top="10vh" custom-class="dialog-padding-none">
                    <div v-if="showView" class="box bg-white hidden-x" style="height:550px;">
                        <js-media-detail :value="form" :preview="false"></js-media-detail>
                    </div>
                </el-dialog>
            </div>
        </el-drawer>
    </div>
</template>
<script>
    module = (function (hxt) {
        return {
            name: '309',
            props: {

            },
            data: function () {
                var _this = this, optor = hxt.store.optor;
                return {
                    optor: optor,
                    list: [],
                    defaultProps: {
                        children: 'children',
                        label: 'label'
                    },
                    filterText: '',
                    typeList: [{ key: 0, value: '目录' }, { key: 1, value: '文档' }],
                    fn: {
                        edit: optor.canDo(30901), root: optor.canDo(30902)
                    },
                    form: {
                        optType: 0,
                        hdPtitle: '',
                        hdId: 0,
                        hdPid: 0,
                        hdType: 0,
                        hdTitle: '',
                        hdStatus: 0,
                        share: 0,
                        pshare: 0,
                        type:0,
                        mediaList: []
                    },
                    drawer: {
                        show: 0,
                        title: ''
                    },
                    oldData: { form: null },
                    msg: null,
                    showView: false,
                    rules: {
                        hdTitle: [
                            { required: true, message: '请输入名称' }
                        ],
                        mediaList: [
                            {
                                validator: function (rule, value, callback) {
                                    if (value.length < 1) return callback(new Error('请至少添加一项文档内容'));
                                    var err = null;
                                    $.each(value, function (idx, item) {
                                        if (item.miType == 1) {
                                            if (!$.trim(item.miTitle)) {
                                                err = '“文字”内容不能为空';
                                                return;
                                            }
                                        }
                                    });
                                    $.each(value, function (idx, item) {
                                        if (item.miType == 5) {
                                            if (!$.trim(item.miTitle)) {
                                                err = '“链接描述”不能为空';
                                                return;
                                            }
                                            if (!$.trim(item.miUrl)) {
                                                err = '“链接”不能为空';
                                                return;
                                            }
                                        }
                                    });
                                    if (!!err) return callback(new Error(err));
                                    callback();
                                }
                            }
                        ]
                    },
                }
            },
            computed: {

            },
            watch: {

            },
            activated: function () {
            },
            mounted: function () {
                var _this = this;
                _this.loadList();
            },
            methods: {
                openEdit: function (show, data, node, share) { //show 1：新增；2：修改；3：删除；
                    var _this = this;
                    //console.log(node)
                    if (show == 1) {
                        if (!_this.optor.bucketName) return hxt.error('暂未设置Bucket名称,请先到【个人信息】提交Bucket名称,才能上传文件');
                        _this.form = { optType: 0, hdPid: data.id, hdId: 0, hdKind: 1, hdType: 0, hdTitle: '', hdStatus: 0, mediaList: [], share: parseInt(share), pshare: share, hdPid : data.id, hdPtitle : data.label };
                        _this.drawer.title = '新建文档（目录）';
                        _this.drawer.show = show;
                        node.expanded = true;
                        return;
                    };
                    if (show == 2) {
                        if (!_this.optor.bucketName) return hxt.error('暂未设置Bucket名称,请先到【个人信息】提交Bucket名称,才能上传文件');
                        hxt.post({
                            url: hxt.config.link + 'pc/HelperDocInfo',
                            data: {
                                hdId: data.id
                            },
                            ok: function (res) {
                                if (res.code != 0) return hxt.error('文档（目录）信息获取失败：' + res.errmsg);
                                _this.form = res.data;
                                _this.form.optType = 1;
                                _this.form.hdPtitle = !!node.parent ? node.parent.data.label : '';
                                _this.form.pshare = node.parent.data.share;
                                _this.drawer.title = '编辑文档（目录）';
                                _this.drawer.show = show;
                                _this.oldData.form = JSON.stringify(_this.form);
                            }
                        });
                        return;
                    };
                    if (show == 3) {
                        var title = data.children.length > 0 ? '删除【{0}】目录，将删除其子项的所有文档（目录），确定删除？'.formatStr(data.label) : ('确定删除【' + data.label + '】' + (data.hdType == 0 ? '目录' : '文档') + ' ？');
                        hxt.confirm(title, function () {
                            hxt.post({
                                url: hxt.config.link + 'pc/HelperDocSave',
                                data: {
                                    optType: 2, hdId: data.id
                                },
                                ok: function (res) {
                                    if (res.code != 0) return hxt.error('删除失败：' + res.errmsg);
                                    hxt.success('删除成功');
                                    const parent = node.parent;
                                    const children = parent.data.children || parent.data;
                                    const index = children.findIndex(function (d) { return d.id === data.id });
                                    children.splice(index, 1);
                                    _this.msg = null;
                                }
                            });

                        });
                        return;
                    };
                    if (show == 4) {
                        //console.log(data, node.parent)
                        var title = ('将“{2}”{1}【{0}】，{3} 是否继续操作？'.formatStr(data.label, data.hdType == 0 ? '目录' : '文档', data.hdStatus != 1 ? '启用' : '停用', data.children.length > 0 && data.hdStatus == 1 ? '注意：其子项的所有文档（目录）也会被停用，' : data.hdPid > 1 && data.hdStatus != 1 ? '注意：其所有的父级目录也会被启用，' : ''));
                        hxt.confirm(title, function () {
                            hxt.post({
                                url: hxt.config.link + 'pc/HelperDocSave',
                                data: { optType: 3, hdId: data.id, hdStatus: data.hdStatus == 1 ? 2 : 1 },
                                ok: function (res) {
                                    if (res.code != 0) {
                                        hxt.alert((data.hdStatus != 1 ? '启用' : '停用') + '失败：' + res.errmsg);
                                        return;
                                    };
                                    hxt.success((data.hdStatus != 1 ? '启用' : '停用') + '成功');
                                    _this.loadList();
                                    //data.hdStatus = data.hdStatus == 1 ? 2 : 1;
                                    //if (data.hdStatus == 2 && data.children.length > 0) {
                                    //    function tree(data) {
                                    //        data.forEach(function (item) {
                                    //            item.hdStatus = 2;
                                    //            if (item.children.length > 0) {
                                    //                tree(item.children)
                                    //            };
                                    //        });
                                    //        return data
                                    //    };
                                    //    data = tree(data.children);
                                    //};
                                }
                            });
                        });
                        return;
                    }
                },
                nodeClick: function (data, node) {
                    //console.log(data, node)
                    var _this = this;
                    if (data.hdType == 0) {
                        //展开or关闭
                        _this.msg = null;
                        if (data.children.length > 0) {
                            node.expanded = !node.expanded
                        };
                        return;
                    };
                    //if (!!_this.msg && _this.msg.hdId == data.id) return;
                    hxt.post({
                        url: hxt.config.link + 'pc/HelperDocInfo',
                        data: {
                            hdId: data.id
                        },
                        ok: function (res) {
                            if (res.code != 0) return hxt.error('文档信息获取失败：' + res.errmsg);
                            _this.msg = res.data;
                        }
                    });
                },
                loadList: function () {
                    var _this = this;
                    hxt.post({
                        url: hxt.config.link + 'pc/HelperDocList',
                        data: {
                            kind: 1
                        },
                        ok: function (res) {
                            if (res.code != 0) return hxt.error('加载系统使用说明列表失败：' + res.errmsg);
                            function tree(data, hdPid) {
                                var arr = []
                                data.forEach(function (item) {
                                    // 先找出第一级
                                    if (item.hdPid === hdPid) {
                                        // 找出第二级
                                        var children = tree(data, item.id)
                                        // console.log(children)
                                        if (children.length) {
                                            // 将二级添加到一级的子级
                                            item.children = children
                                        }
                                        // 收集一级
                                        arr.push(item)
                                    }
                                })
                                return arr
                            };

                            var list = res.data.map(function (item) {
                                return { id: item.hdId, label: item.hdTitle, hdPid: item.hdPid, hdType: item.hdType, miKey: item.miKey, hdStatus: item.hdStatus, oiId: item.oiId,oiName: item.oiName, makeTime: item.makeTime, share: item.share, children: [] }
                            });
                            _this.list = tree(list, 0);
                        }
                    });
                },
                getFileIco: function (name) {
                    return hxt.getFileIco(name);
                },

                view: function () {
                    this.form.makeTime = hxt.dateFormat('yyyy年MM月dd日 HH:mm:ss');
                    this.form.oiName = this.optor.uiName;
                    this.showView = true;
                },
                submit: function (e) {
                    var _this = this;
                    hxt.validateElForm(_this, 'form', function () {
                        if (_this.oldData.form == JSON.stringify(_this.form)) return hxt.msg('信息未更改');
                        var title = _this.form.hdType == 0 ? '确定保存此目录?' : '确定保存此文档?';
                        hxt.confirm(title, function () {
                            var saveToServer = function () {
                                hxt.unmask();
                                var data = JSON.parse(JSON.stringify(_this.form))
                                    , mediaList = data.mediaList.map(function (item, index) {
                                        return {
                                            miId: item.miId,
                                            miDuration: item.miDuration,
                                            miIndex: index,
                                            miSize: item.miSize,
                                            miTitle: item.miTitle,
                                            miType: item.miType,
                                            miUrl: item.miUrl
                                        }
                                    });
                                //console.log(data);
                                data.mediaList = data.hdType == 1 ? encodeURIComponent(JSON.stringify(mediaList)) : "";
                                hxt.post({
                                    url: hxt.config.link + 'pc/HelperDocSave',
                                    data: data,
                                    ok: function (res) {
                                        if (res.code != 0) return hxt.error('保存失败：' + res.errmsg);
                                        hxt.success('保存成功');
                                                _this.loadList();
                                                _this.msg = null;
                                                _this.drawer.show = 0;
                                    }
                                });
                            };
                            var upload = function () {
                                var row = _this.form.mediaList.find(function (item) {
                                    var url = ('' + item.miUrl).toLowerCase();
                                    return item.miType != 1 && item.miType != 5 && !url.startsWith('http://') && !url.startsWith('https://');
                                });
                                if (!!row) {
                                    //setTimeout(function () {
                                    //    row.miUrl = row.miType == 2 ? 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg' : 'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4';
                                    //    if (row.miType == 3 || row.miType == 4) row.rawUrl = null;
                                    //    upload();
                                    //}, 500);
                                    hxt.uploadFile({
                                        signUrl: hxt.config.link + 'pc/v3OssToken',
                                        base64: row.miType == 2 ? row.miUrl : null,
                                        file: row.miType != 2 ? row.miUrl : null,
                                        compress: false,
                                        folder: _this.optor.bucketName + '/helper' + (row.miType == 2 ? '/img' : row.miType == 3 ? '/mp3' : row.miType == 4?'/mp4':'/file'),
                                        success: function (res) {
                                            row.miUrl = res.url;
                                            upload();
                                        },
                                        fail: function (err) {
                                            hxt.unmask();
                                            hxt.error('上传文件失败：' + err);
                                        }
                                    });
                                }
                                else {
                                    saveToServer();
                                }
                            };
                            hxt.mask();
                            upload();
                        });
                    });
                }
            },
            components: {
                jsMedia: function () { return hxt.staticComponent(@Html.Raw(this.vueComponent("~/Views/pc/My/Component/pc.media.cshtml"))); },
                jsMediaDetail: function () { return hxt.staticComponent(@Html.Raw(this.vueComponent("~/Views/pc/My/Component/pc.media.detail.cshtml"))); }
            }
        };
    })(window.$jscript.fn);
</script>
<style>
    #title-container .el-input__inner {
        font-size: 30px;
        font-family: '宋体';
        font-weight: bold;
        color: black;
        border: none !important;
        outline: none;
        width: 100%;
    }
</style>